package mock;

import cn.ibabygroup.commons.authority.exception.AuthException;
import cn.ibabygroup.commons.authority.util.ErrorCode;
import cn.ibabygroup.commons.authority.util.SecurityUtil;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.util.StringUtils;

/**
 * Created by Crowhyc on 2016/5/23.
 */
public class UserTester extends BeforeTester {

    @Test
    public void testLoginNull() throws Exception {
        MvcResult mvcResult = getMockMvcResult(MockMvcRequestBuilders.post("/user/login").param("username", "").param("password", "")).
                andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn();
        JSONObject object = new JSONObject(mvcResult.getResponse().getContentAsString());
        Assert.assertEquals(2, object.getInt("Code"));
    }


    @Test
    public void testLoginTokenValidate() throws Exception {
        MvcResult mvcResult = getMockMvcResult(MockMvcRequestBuilders.post("/user/login").param("username", "crowhyc").param("password", "123456")).andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn();
        JSONObject jsonObject = new JSONObject(mvcResult.getResponse().getContentAsString());
        Assert.assertTrue(checkToken(jsonObject.getString("Data")));
    }

    private boolean checkToken(String token) throws Exception {
        String key = "Share2015&IBaby1";
        if (StringUtils.isEmpty(token) || token.equals("null"))
            throw new AuthException("没有找到token", ErrorCode.TOKEN_NOT_FOUND);
        String tokenStr = SecurityUtil.decrypt(token, key);
        if (StringUtils.isEmpty(tokenStr))
            throw new AuthException("解析token异常", ErrorCode.TOKEN_INVALID);
        if (tokenStr.length() < 14)
            throw new AuthException("token长度不够", ErrorCode.TOKEN_INVALID);
        if (tokenStr.length() == 14)
            throw new AuthException("没有找到证书信息", ErrorCode.TOKEN_INVALID);
        String dCertStr = tokenStr.substring(0, tokenStr.length() - 14);
        String certStr = SecurityUtil.decrypt(dCertStr, key);
        if (StringUtils.isEmpty(certStr))
            throw new AuthException("解析证书信息异常", ErrorCode.SYS_ERROR);
        return true;
    }
}
